package pro16;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Price {
    public static void main(String[] args) {
        String fileName = "C:\\Users\\yueli\\Desktop\\price.txt";
        double Price = 0; 
        int count = 0; 
        try (BufferedReader pr = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = pr.readLine()) != null) {
                String[] parts = line.split(" ");
                for (String part : parts) {
                    if (part.matches("\\d+/台")) {
                        double price = Double.parseDouble(part.replace("/台", ""));
                        Price += price;
                        count++;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (count > 0) {
            double averagePrice = Price / count;
            System.out.printf("平均价格: %.2f 元/台%n", averagePrice);
            appendAveragePriceToFile(fileName, averagePrice);
        } else {
            System.out.println("没有找到价格数据。");
        }
    }

    private static void appendAveragePriceToFile(String fileName, double averagePrice) {
        try (FileWriter fw = new FileWriter(fileName, true)) {
            fw.write(String.format("平均价格: %.2f 元/台%n", averagePrice));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
